package com.bms.zuul.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author thinknovo
 * @version 1.0
 * @description MyLogoutFilter.java
 */
public class MyLogoutFilter extends LogoutFilter {
    public MyLogoutFilter() {
        System.out.println("MyLogoutFilter构造函数~~~~~~~~~~~");
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        System.out.println("自定义 MyLogoutFilter----------------");
        //在这里执行退出系统前需要清空的数据
        Subject subject = getSubject(request, response);
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //推出提示
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        ObjectMapper json = new ObjectMapper();
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("msg","退出成功");
        System.out.println(map);
        out.print(json.writeValueAsString(map));
        out.flush();
        out.close();

        ServletContext context = request.getServletContext();
        try {
            //核心推出方法
            subject.logout();
            context.removeAttribute("error");
        } catch (SessionException e) {
            e.printStackTrace();
        }
        return false;
    }
}
